package com.youlei.newgraduateproject.config;

import com.youlei.newgraduateproject.security.JwtAuthenticationEntryPoint;
import com.youlei.newgraduateproject.security.UserDetailServiceImpl;
import com.youlei.newgraduateproject.security.filter.CaptchaFilter;
import com.youlei.newgraduateproject.security.filter.JwtAuthenticationFilter;
import com.youlei.newgraduateproject.security.handler.JwtAccessDeniedHandler;
import com.youlei.newgraduateproject.security.handler.JwtLogoutSuccessHandler;
import com.youlei.newgraduateproject.security.handler.LoginFailureHandler;
import com.youlei.newgraduateproject.security.handler.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author youlei
 * @version 1.0
 * @Date 2021-05-09-9:54
 * Spring Security核心配置类
 */

/**
 * 使用表达式时间方法级别的安全性 4个注解可用
 *
 * @PreAuthorize 在方法调用之前, 基于表达式的计算结果来限制对方法的访问
 * @PostAuthorize 允许方法调用, 但是如果表达式计算结果为false, 将抛出一个安全性异常
 * @PostFilter 允许方法调用, 但必须按照表达式来过滤方法的结果
 * @PreFilter 允许方法调用, 但必须在进入方法之前过滤输入值
 */
@EnableGlobalMethodSecurity(prePostEnabled = true)
//开启Security相关的安全策略的配置
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    LoginFailureHandler loginFailureHandler;
    @Autowired
    LoginSuccessHandler loginSuccessHandler;
    @Autowired
    JwtLogoutSuccessHandler jwtLogoutSuccessHandler;
    @Autowired
    CaptchaFilter captchaFilter;
    @Autowired
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    @Autowired
    JwtAccessDeniedHandler jwtAccessDeniedHandler;
    @Autowired
    UserDetailServiceImpl userDetailService;

    @Bean
    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager());
        return jwtAuthenticationFilter;
    }
    //配置password加密形式
    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //白名单,配置不需要拦截的请求
    public static final String[] URL_WHITELIST = {
            "/webjars/**",
            "/favicon.ico",
            "/captcha",
            //"/login",
            "/logout",
            //"/test/*",
            //"/test",
            // -- swagger ui
            "/swagger-resources/**",
            "/swagger-ui.html",
            "/v2/api-docs",
            "/v3/api-docs",
            "/webjars/**",
            "/doc.html"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()

                .and()
                    //SpringSecurity中默认开启了CSRF（Cross-site request forgery跨站请求伪造)
                    //CSRF和RESTful技术有冲突。CSRF默认支持的方法： GET|HEAD|TRACE|OPTIONS，不支持POST。
                    .csrf().disable()
                    //登录配置 登录成功的处理器和登录失败的处理器
                    .formLogin()
                        .successHandler(loginSuccessHandler)
                        .failureHandler(loginFailureHandler)
                .and()
                    //注销配置 退出成功处理器
                    .logout()
                    .logoutSuccessHandler(jwtLogoutSuccessHandler)

                .and()
                    //配置拦截规则
                    .authorizeRequests()
                    //配置白名单
                    .antMatchers(URL_WHITELIST).permitAll()
                    //除白名单外的请求都要进行认证
                    .anyRequest().authenticated()

                .and()
                    //禁用session,不生成session
                    /**
                     *  ALWAYS 总是创建HttpSession
                     *  IF_REQUIRED Spring Security只会在需要时创建一个HttpSession
                     *  NEVER SpringSecurity不会创建HttpSession，但如果它已经存在，将可以使用HttpSession
                     *  STATELESS SpringSecurity永远不会创建HttpSession，它不会使用HttpSession来获取SecurityContext
                     */
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)


                .and()
                    //异常处理配置
                    .exceptionHandling()
                    .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                    .accessDeniedHandler(jwtAccessDeniedHandler)

                .and()
                    //将自定义拦截器captchaFilter验证码过滤器
                    //置于UsernamePasswordAuthenticationFilter用户名密码过滤器之前
                    //.addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)
                    .addFilter(jwtAuthenticationFilter())
        ;
    }

    //将userDetailsService注入到spring security中
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService);
    }
}
